/*
 * --------------------
 * Company					: LUOYANG GINGKO TECHNOLOGY CO.,LTD.
 * BBS						: http://www.eeschool.org
 * --------------------
 * Project Name			: USART
 * Module Name				: BPS_Ctrl
 * Description				: The codes of "BPS_Ctrl"
 * --------------------
 * Tool Versions			: Quartus II 13.1
 * Target Device			: Cyclone IV E  EP4CE10F17C8
 * --------------------
 * Engineer					: xiaorenwu
 * Revision					: V0.0
 * Created Date			: 2016-04-06
 * --------------------
 * Engineer					:
 * Revision					:
 * Modified Date			:
 * --------------------
 * Additional Comments	:
 *
 * --------------------
 */

//--------------------Timescale------------------------------//
`timescale 1 ns / 1 ps

//--------------------Module_BPS_Ctrl-----------------------//
	module BPS_Ctrl(
						input CLK_25M,
						input rst_n,
						output BPS_CLK,
						input[1:0] wire_state
						);
			
	always @(posedge CLK_25M or negedge rst_n)
		if (!rst_n)
			begin
				Baud <= BPS_9600;//2603
			end
		else
			begin
				case(wire_state)
					2'b00:
						begin
							Baud <= BPS_9600;
						end
					2'b01:
						begin
							Baud <= BPS_38400;
						end
					2'b10:
						begin
							Baud <= BPS_115200;
						end
					default:;
				endcase
			end
//--------------------Master_CLK-----------------------------//
	wire CLK = CLK_25M;

//--------------------BPS_Parameter--------------------------//
	localparam	BPS_9600 = 12'd2603,	//波特率为9600bps-------------1s振荡9600次
					BPS_19200 = 12'd1301,	//波特率为19200bps
					BPS_38400 = 12'd650,	//波特率为38400bps
					BPS_57600 = 12'd433,	//波特率为57600bps
					BPS_115200 = 12'd216; //波特率为115200bps
	reg[11:0]Baud = BPS_9600;	//参照上面参数,得到不同的波特率
	
//--------------------BPS_CLK--------------------------------//	
	reg BPS_CLK_r;
	reg [11:0]cnt = 12'd0;
	
	always @(posedge CLK_25M or negedge rst_n)
		if (!rst_n)
			cnt <= 12'd0;
		else if(cnt == Baud)
			cnt <= 12'd0;
		else cnt = cnt + 1'd1;

	always @(posedge CLK_25M or negedge rst_n)
		if (!rst_n)
			BPS_CLK_r <= 1'd0;
		else if (cnt <= Baud >> 1) //相当于Baud/2
			BPS_CLK_r <= 1'd0;	//作为接收数据时的中间采样点,或发送数据时的位分界点
		else
			BPS_CLK_r <= 1'd1;

	assign BPS_CLK = BPS_CLK_r; //BPS_CLK即为所需的波特率

//--------------------Endmodule------------------------------//	
	endmodule
